package com.golden.order02.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class WordTempleteUtils {
    private  static Configuration configuration = null;
    private  String templateFolder ;

    public WordTempleteUtils(String tempFolder) {
    	
    	configuration =new Configuration();
    	
        configuration.setDefaultEncoding("utf-8");
        try {
            templateFolder = tempFolder;
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public  File createDoc(Map<?, ?> dataMap, String ftlFile, String outFile) {
        File f = new File(outFile);
        try {
            Template freemarkerTemplate = configuration.getTemplate(ftlFile);
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            freemarkerTemplate.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
    /**
     * @param source  源
     * @param stencil  模版文件
     * @param aims  目标文件
     * @param data  数据
     */
    public static boolean generate(String source ,String stencil,String aims,Map<String, Object> data) {
    	
    	WordTempleteUtils f=new WordTempleteUtils(source);
    	
    	try {
			f.createDoc(data, stencil, aims);
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
    	
    	return true;
    }
    
    
}
